package org.jeecg.modules.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.mes.entity.MesProductionPlan;
import org.jeecg.modules.mes.entity.MesProductionPlanTask;
import org.jeecg.modules.mes.entity.MesTaskParticipant;
import org.jeecg.modules.mes.service.IMesProductionPlanService;
import org.jeecg.modules.mes.service.IMesProductionPlanTaskService;
import org.jeecg.modules.mes.service.IMesTaskParticipantService;
import org.jeecg.modules.mes.vo.TaskClaimVO;
import org.jeecg.modules.mes.vo.BatchTaskCompleteVO;
import org.jeecg.modules.mes.vo.TaskCompleteVO;
import org.jeecg.modules.mes.vo.TaskProgressUpdateVO;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * @Description: 生产计划工种任务管理
 * @Author: jeecg-boot
 * @Date: 2025-01-21
 * @Version: V1.0
 */
@Api(tags = "生产任务管理")
@RestController
@RequestMapping("/mes/task")
@Slf4j
public class MesProductionPlanTaskController extends JeecgController<MesProductionPlanTask, IMesProductionPlanTaskService> {

    @Autowired
    private IMesProductionPlanTaskService mesProductionPlanTaskService;

    @Autowired
    private IMesTaskParticipantService taskParticipantService;

    @Autowired
    private IMesProductionPlanService planService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "生产任务-分页列表查询")
    @ApiOperation(value = "生产任务-分页列表查询", notes = "生产任务-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesProductionPlanTask>> queryPageList(MesProductionPlanTask mesProductionPlanTask,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据条件查询
        if (mesProductionPlanTask.getPlanName() != null && !mesProductionPlanTask.getPlanName().isEmpty()) {
            List<Object> planIdList = planService.listObjs(new LambdaQueryWrapper<MesProductionPlan>()
                    .select(MesProductionPlan::getId)
                    .like(MesProductionPlan::getPlanName, mesProductionPlanTask.getPlanName()));
            if (planIdList != null && !planIdList.isEmpty()) {
                queryWrapper.in(MesProductionPlanTask::getPlanId, planIdList);
            } else {
                // 如果没有找到匹配的计划，返回空结果
                queryWrapper.eq(MesProductionPlanTask::getId, "");
            }
        }
        if(mesProductionPlanTask.getPlanId() != null && !mesProductionPlanTask.getPlanId().isEmpty()){
            queryWrapper.eq(MesProductionPlanTask::getPlanId, mesProductionPlanTask.getPlanId());
        }
        if (mesProductionPlanTask.getWorkTypeId() != null && !mesProductionPlanTask.getWorkTypeId().isEmpty()) {
            queryWrapper.eq(MesProductionPlanTask::getWorkTypeId, mesProductionPlanTask.getWorkTypeId());
        }
        if (mesProductionPlanTask.getStatus() != null) {
            queryWrapper.eq(MesProductionPlanTask::getStatus, mesProductionPlanTask.getStatus());
        }

        if(mesProductionPlanTask.getClaimedEmployeeId() != null && !mesProductionPlanTask.getClaimedEmployeeId().isEmpty()){
            //查询任务参与信息获取任务id
            List<Object> taskIds = taskParticipantService.listObjs(new LambdaQueryWrapper<MesTaskParticipant>()
                    .select(MesTaskParticipant::getTaskId)
                    .eq(MesTaskParticipant::getEmployeeId, mesProductionPlanTask.getClaimedEmployeeId()));
            if(taskIds != null && !taskIds.isEmpty()){
                queryWrapper.in(MesProductionPlanTask::getId, taskIds);
            } else {
                // 如果没有找到匹配的任务，返回空结果
                queryWrapper.eq(MesProductionPlanTask::getId, "");
            }
        }
        // 通过参与者表查询员工相关任务
        String employeeId = req.getParameter("employeeId");
        if (employeeId != null && !employeeId.isEmpty()) {
            List<MesTaskParticipant> participants = taskParticipantService.getEmployeeParticipations(employeeId, null);
            if (participants != null && !participants.isEmpty()) {
                List<String> taskIds = participants.stream()
                        .map(MesTaskParticipant::getTaskId)
                        .collect(java.util.stream.Collectors.toList());
                queryWrapper.in(MesProductionPlanTask::getId, taskIds);
            } else {
                // 如果没有参与记录，返回空结果
                queryWrapper.eq(MesProductionPlanTask::getId, "");
            }
        }
        
        // 只显示已下发的生产计划的任务（生产计划状态 >= 2）
        queryWrapper.exists("SELECT 1 FROM mes_production_plan p WHERE p.id = mes_production_plan_task.plan_id AND p.status >= 2");
        
        queryWrapper.orderByAsc(MesProductionPlanTask::getSequence);
        queryWrapper.orderByAsc(MesProductionPlanTask::getStatus);
        queryWrapper.orderByAsc(MesProductionPlanTask::getProductInfo);
        
        Page<MesProductionPlanTask> page = new Page<>(pageNo, pageSize);
        IPage<MesProductionPlanTask> pageList = mesProductionPlanTaskService.page(page, queryWrapper);
        
        if (!pageList.getRecords().isEmpty()) {
            // 批量获取计划信息，避免N+1查询
            List<String> planIds = pageList.getRecords().stream()
                    .map(MesProductionPlanTask::getPlanId)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());
            
            Map<String, String> planNameMap = new HashMap<>();
            if (!planIds.isEmpty()) {
                List<MesProductionPlan> plans = planService.listByIds(planIds);
                planNameMap = plans.stream()
                        .collect(java.util.stream.Collectors.toMap(
                                MesProductionPlan::getId, 
                                MesProductionPlan::getPlanName));
            }
            
            // 批量获取任务参与者信息，避免N+1查询
            List<String> taskIds = pageList.getRecords().stream()
                    .map(MesProductionPlanTask::getId)
                    .collect(java.util.stream.Collectors.toList());
            
            Map<String, List<MesTaskParticipant>> participantMap = new HashMap<>();
            if (!taskIds.isEmpty()) {
                List<MesTaskParticipant> allParticipants = taskParticipantService.list(
                        new LambdaQueryWrapper<MesTaskParticipant>()
                                .in(MesTaskParticipant::getTaskId, taskIds));
                participantMap = allParticipants.stream()
                        .collect(java.util.stream.Collectors.groupingBy(MesTaskParticipant::getTaskId));
            }
            
            // 为每个任务设置参与者信息和计划名称
            for (MesProductionPlanTask task : pageList.getRecords()) {
                // 设置计划名称
                task.setPlanName(planNameMap.get(task.getPlanId()));
                
                // 设置参与者信息
                List<MesTaskParticipant> participants = participantMap.get(task.getId());
                if (participants != null && !participants.isEmpty()) {
                    task.setParticipants(participants);
                    String participantNames = participants.stream()
                            .map(MesTaskParticipant::getEmployeeName)
                            .collect(java.util.stream.Collectors.joining(","));
                    task.setParticipantNames(participantNames);
                }
            }
        }
        
        return Result.OK(pageList);
    }

    /**
     * 获取可领取的任务列表
     */
    @AutoLog(value = "获取可领取的任务列表")
    @ApiOperation(value = "获取可领取的任务列表", notes = "根据员工工种获取可领取的任务")
    @GetMapping(value = "/available")
    public Result<IPage<MesProductionPlanTask>> getAvailableTasks(@RequestParam String employeeId,
                                                                  @RequestParam(required = false) String planId,
                                                                  @RequestParam(required = false) String workTypeId,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest req) {
        try {
            LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
            
            // 只查询待领取的任务（状态为0）
            queryWrapper.eq(MesProductionPlanTask::getStatus, 0);

            if(planId != null && !planId.isEmpty()){
                queryWrapper.eq(MesProductionPlanTask::getPlanId, planId);
            }
            
            // 根据工种筛选
            if (workTypeId != null && !workTypeId.isEmpty()) {
                queryWrapper.eq(MesProductionPlanTask::getWorkTypeId, workTypeId);
            }
            
            // 只显示已下发的生产计划的任务（生产计划状态 >= 2）
            queryWrapper.exists("SELECT 1 FROM mes_production_plan p WHERE p.id = mes_production_plan_task.plan_id AND p.status >= 2");
            
            // 根据员工工种匹配可领取的任务
            queryWrapper.exists("SELECT 1 FROM mes_employee_work_type ewt WHERE ewt.employee_id = '" + employeeId + "' AND ewt.work_type_id = mes_production_plan_task.work_type_id");
            
            queryWrapper.orderByAsc(MesProductionPlanTask::getSequence);
            queryWrapper.orderByAsc(MesProductionPlanTask::getStatus);
            queryWrapper.orderByAsc(MesProductionPlanTask::getProductInfo);
            
            Page<MesProductionPlanTask> page = new Page<>(pageNo, pageSize);
            IPage<MesProductionPlanTask> pageList = mesProductionPlanTaskService.page(page, queryWrapper);
            
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error("获取可领取任务失败", e);
            return Result.error("获取可领取任务失败：" + e.getMessage());
        }
    }

    /**
     * 员工领取任务
     */
    @AutoLog(value = "员工领取任务")
    @ApiOperation(value = "员工领取任务", notes = "员工领取指定任务")
    @PostMapping(value = "/claim")
    public Result<String> claimTask(@RequestBody TaskClaimVO claimVO) {
        try {
            mesProductionPlanTaskService.claimTask(claimVO.getTaskId(), claimVO.getEmployeeId(), claimVO.getRemark());
            return Result.OK("任务领取成功！");
        } catch (Exception e) {
            log.error("任务领取失败", e);
            return Result.error("任务领取失败：" + e.getMessage());
        }
    }

    /**
     * 批量完成任务
     */
    @PostMapping(value = "/batch-complete")
    public Result<String> batchCompleteTask(@RequestBody BatchTaskCompleteVO batchCompleteVO) {
        try {
            mesProductionPlanTaskService.batchCompleteTask(batchCompleteVO);
            return Result.OK("批量完成任务成功！");
        } catch (Exception e) {
            log.error("批量完成任务失败", e);
            return Result.error("批量完成任务失败：" + e.getMessage());
        }
    }

    /**
     * 获取分组任务数据（用于Web端分组视图）
     */
    @AutoLog(value = "获取分组任务数据")
    @ApiOperation(value = "获取分组任务数据", notes = "按生产计划分组显示任务数据")
    @GetMapping(value = "/grouped")
    public Result<Object> getGroupedTaskData(MesProductionPlanTask queryParam,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                           HttpServletRequest req) {
        try {
            Object result = mesProductionPlanTaskService.getGroupedTaskData(queryParam, pageNo, pageSize);
            return Result.OK(result);
        } catch (Exception e) {
            log.error("获取分组任务数据失败", e);
            return Result.error("获取分组任务数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取我的任务列表
     */
    @AutoLog(value = "获取我的任务列表")
    @ApiOperation(value = "获取我的任务列表", notes = "获取员工已领取的任务列表")
    @GetMapping(value = "/my-tasks")
    public Result<IPage<MesProductionPlanTask>> getMyTasks(@RequestParam String employeeId,
                                                           @RequestParam(required = false) String planId,
                                                           @RequestParam(required = false) Integer status,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        try {
            LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();

            // 通过参与者表获取员工的任务ID列表
            List<MesTaskParticipant> participants = taskParticipantService.getEmployeeParticipations(employeeId, status);
            if (participants.isEmpty()) {
                // 如果没有参与记录，返回空结果
                queryWrapper.eq(MesProductionPlanTask::getId, "");
            } else {
                List<String> taskIds = participants.stream()
                        .map(MesTaskParticipant::getTaskId)
                        .collect(java.util.stream.Collectors.toList());
                queryWrapper.in(MesProductionPlanTask::getId, taskIds);
            }
            
            // 根据状态筛选0-待领取,1-已领取,2-进行中,3-已完成,4-暂停,5-部分领取
            if (status != null) {
                queryWrapper.eq(MesProductionPlanTask::getStatus, status);
            } else {
                // 默认查询已领取但未完成的任务（状态1,2,4）
                queryWrapper.in(MesProductionPlanTask::getStatus, Arrays.asList(1, 2, 4,5));
            }

            if(planId != null && !planId.isEmpty()){
                queryWrapper.eq(MesProductionPlanTask::getPlanId, planId);
            }
            
            // 只显示已下发的生产计划的任务（生产计划状态 >= 2）
            queryWrapper.exists("SELECT 1 FROM mes_production_plan p WHERE p.id = mes_production_plan_task.plan_id AND p.status >= 2");

            queryWrapper.orderByDesc(MesProductionPlanTask::getCreateTime);
            queryWrapper.orderByAsc(MesProductionPlanTask::getStatus);
            queryWrapper.orderByAsc(MesProductionPlanTask::getProductInfo);
            
            Page<MesProductionPlanTask> page = new Page<>(pageNo, pageSize);
            IPage<MesProductionPlanTask> pageList = mesProductionPlanTaskService.page(page, queryWrapper);
            
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error("获取我的任务失败", e);
            return Result.error("获取我的任务失败：" + e.getMessage());
        }
    }

    /**
     * 提交任务（原开始执行任务）
     */
    @AutoLog(value = "提交任务")
    @ApiOperation(value = "提交任务", notes = "员工提交已领取的任务，开始时间设为领取时间，提交时间设为当前时间")
    @PostMapping(value = "/submit")
    public Result<String> submitTask(@RequestParam String taskId, @RequestParam String employeeId) {
        try {
            mesProductionPlanTaskService.submitTask(taskId, employeeId);
            return Result.OK("任务提交成功！");
        } catch (Exception e) {
            log.error("提交任务失败", e);
            return Result.error("提交任务失败：" + e.getMessage());
        }
    }

    /**
     * 暂停任务
     */
    @AutoLog(value = "暂停任务")
    @ApiOperation(value = "暂停任务", notes = "暂停正在执行的任务")
    @PostMapping(value = "/pause")
    public Result<String> pauseTask(@RequestParam String taskId, @RequestParam String employeeId) {
        try {
            mesProductionPlanTaskService.pauseTask(taskId, employeeId);
            return Result.OK("任务已暂停！");
        } catch (Exception e) {
            log.error("暂停任务失败", e);
            return Result.error("暂停任务失败：" + e.getMessage());
        }
    }

    /**
     * 恢复任务
     */
    @AutoLog(value = "恢复任务")
    @ApiOperation(value = "恢复任务", notes = "恢复暂停的任务")
    @PostMapping(value = "/resume")
    public Result<String> resumeTask(@RequestParam String taskId, @RequestParam String employeeId) {
        try {
            mesProductionPlanTaskService.resumeTask(taskId, employeeId);
            return Result.OK("任务已恢复！");
        } catch (Exception e) {
            log.error("恢复任务失败", e);
            return Result.error("恢复任务失败：" + e.getMessage());
        }
    }

    /**
     * 完成任务
     */
    @AutoLog(value = "完成任务")
    @ApiOperation(value = "完成任务", notes = "完成正在执行的任务")
    @PostMapping(value = "/complete")
    public Result<String> completeTask(@RequestBody TaskCompleteVO completeVO) {
        try {
            mesProductionPlanTaskService.completeTask(
                completeVO.getTaskId(), 
                completeVO.getEmployeeId(), 
                completeVO.getCompletedQuantity(), 
                completeVO.getRemark()
            );
            return Result.OK("任务完成！");
        } catch (Exception e) {
            log.error("完成任务失败", e);
            return Result.error("完成任务失败：" + e.getMessage());
        }
    }

    /**
     * 更新任务进度
     */
    @AutoLog(value = "更新任务进度")
    @ApiOperation(value = "更新任务进度", notes = "更新正在执行任务的进度")
    @PostMapping(value = "/update-progress")
    public Result<String> updateTaskProgress(@RequestBody TaskProgressUpdateVO progressVO) {
        try {
            mesProductionPlanTaskService.updateTaskProgress(
                progressVO.getTaskId(), 
                progressVO.getCompletedQuantity(), 
                progressVO.getRemark()
            );
            return Result.OK("进度更新成功！");
        } catch (Exception e) {
            log.error("更新任务进度失败", e);
            return Result.error("更新任务进度失败：" + e.getMessage());
        }
    }

    /**
     * 获取任务详情
     */
    @AutoLog(value = "获取任务详情")
    @ApiOperation(value = "获取任务详情", notes = "根据ID获取任务详情")
    @GetMapping(value = "/detail/{id}")
    public Result<MesProductionPlanTask> getDetail(@PathVariable("id") String id) {
        try {
            MesProductionPlanTask task = mesProductionPlanTaskService.getById(id);
            if (task == null) {
                return Result.error("任务不存在");
            }
            return Result.OK(task);
        } catch (Exception e) {
            log.error("获取任务详情失败", e);
            return Result.error("获取任务详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取员工任务统计
     */
    @AutoLog(value = "获取员工任务统计")
    @ApiOperation(value = "获取员工任务统计", notes = "获取员工的任务统计信息")
    @GetMapping(value = "/statistics/{employeeId}")
    public Result<Object> getEmployeeTaskStatistics(@PathVariable("employeeId") String employeeId) {
        try {
            Object statistics = mesProductionPlanTaskService.getEmployeeTaskStatistics(employeeId);
            return Result.OK(statistics);
        } catch (Exception e) {
            log.error("获取员工任务统计失败", e);
            return Result.error("获取员工任务统计失败：" + e.getMessage());
        }
    }

    /**
     * 根据计划ID获取任务列表
     */
    @AutoLog(value = "根据计划ID获取任务列表")
    @ApiOperation(value = "根据计划ID获取任务列表", notes = "根据生产计划ID获取所有任务")
    @GetMapping(value = "/by-plan/{planId}")
    public Result<List<MesProductionPlanTask>> getTasksByPlanId(@PathVariable("planId") String planId) {
        try {
            List<MesProductionPlanTask> tasks = mesProductionPlanTaskService.getTasksByPlanId(planId);
            return Result.OK(tasks);
        } catch (Exception e) {
            log.error("获取计划任务列表失败", e);
            return Result.error("获取计划任务列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取员工历史任务列表
     */
    @AutoLog(value = "获取员工历史任务列表")
    @ApiOperation(value = "获取员工历史任务列表", notes = "获取员工已完成的历史任务")
    @GetMapping(value = "/history")
    public Result<IPage<MesProductionPlanTask>> getHistoryTasks(@RequestParam String employeeId,
                                                                @RequestParam(required = false) String planId,
                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                HttpServletRequest req) {
        try {
            LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
            if(planId != null && !planId.isEmpty()){
                queryWrapper.eq(MesProductionPlanTask::getPlanId, planId);
            }
            
            // 通过参与者表获取该员工已完成的任务
            List<MesTaskParticipant> participants = taskParticipantService.getEmployeeParticipations(employeeId, null);
            List<String> taskIds = participants.stream().map(MesTaskParticipant::getTaskId).collect(Collectors.toList());
            
            if (taskIds.isEmpty()) {
                return Result.OK();
            }
            
            queryWrapper.in(MesProductionPlanTask::getId, taskIds);
            queryWrapper.eq(MesProductionPlanTask::getStatus, 3);

            queryWrapper.orderByDesc(MesProductionPlanTask::getCreateTime);
            queryWrapper.orderByAsc(MesProductionPlanTask::getStatus);
            queryWrapper.orderByAsc(MesProductionPlanTask::getProductInfo);
            
            Page<MesProductionPlanTask> page = new Page<>(pageNo, pageSize);
            IPage<MesProductionPlanTask> pageList = mesProductionPlanTaskService.page(page, queryWrapper);
            
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error("获取员工历史任务失败", e);
            return Result.error("获取员工历史任务失败：" + e.getMessage());
        }
    }

    /**
     * 撤回任务
     */
    @AutoLog(value = "撤回任务")
    @ApiOperation(value = "撤回任务", notes = "员工撤回已领取的任务，恢复为未领取状态")
    @PostMapping(value = "/withdraw")
    public Result<String> withdrawTasks(@RequestBody java.util.Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            java.util.List<String> taskIds = (java.util.List<String>) params.get("taskIds");
            String employeeId = (String) params.get("employeeId");
            
            if (taskIds == null || taskIds.isEmpty()) {
                return Result.error("请选择要撤回的任务");
            }
            
            mesProductionPlanTaskService.withdrawTasks(taskIds, employeeId);
            return Result.OK("任务撤回成功！");
        } catch (Exception e) {
            log.error("撤回任务失败", e);
            return Result.error("撤回任务失败：" + e.getMessage());
        }
    }

    /**
     * 获取计划任务统计信息
     */
    @AutoLog(value = "获取计划任务统计信息")
    @ApiOperation(value = "获取计划任务统计信息", notes = "获取指定计划的任务统计信息")
    @GetMapping(value = "/statistics")
    public Result<Map<String, Object>> getTaskStatistics(@RequestParam String planId) {
        try {
            LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MesProductionPlanTask::getPlanId, planId);
            
            List<MesProductionPlanTask> tasks = mesProductionPlanTaskService.list(queryWrapper);
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalTasks", tasks.size());
            statistics.put("pendingTasks", tasks.stream().mapToInt(task -> task.getStatus() == 0 ? 1 : 0).sum());
            statistics.put("inProgressTasks", tasks.stream().mapToInt(task -> (task.getStatus() == 1 || task.getStatus() == 2) ? 1 : 0).sum());
            statistics.put("completedTasks", tasks.stream().mapToInt(task -> task.getStatus() == 3 ? 1 : 0).sum());
            
            return Result.OK(statistics);
        } catch (Exception e) {
            log.error("获取任务统计信息失败", e);
            return Result.error("获取任务统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取员工工作统计数据
     */
    @AutoLog(value = "获取员工工作统计数据")
    @ApiOperation(value = "获取员工工作统计数据", notes = "根据员工ID和日期范围获取工作统计数据")
    @GetMapping(value = "/employeeWorkStatistics")
    public Result<Map<String, Object>> getEmployeeWorkStatistics(
            @RequestParam String employeeId,
            @RequestParam @org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd") java.util.Date startDate,
            @RequestParam @org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd") java.util.Date endDate) {
        try {
            // 获取员工在指定日期范围内参与的任务
            List<MesTaskParticipant> participants = taskParticipantService.getEmployeeParticipations(employeeId, null);
            
            if (participants == null || participants.isEmpty()) {
                Map<String, Object> emptyStats = new HashMap<>();
                emptyStats.put("totalTasks", 0);
                emptyStats.put("completedTasks", 0);
                emptyStats.put("ongoingTasks", 0);
                emptyStats.put("pendingTasks", 0);
                emptyStats.put("workHours", 0.0);
                return Result.OK(emptyStats);
            }
            
            List<String> taskIds = participants.stream()
                    .map(MesTaskParticipant::getTaskId)
                    .collect(java.util.stream.Collectors.toList());
            
            // 查询任务详情
            LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(MesProductionPlanTask::getId, taskIds);
            
            // 添加日期范围过滤（基于计划开始日期）
            queryWrapper.ge(MesProductionPlanTask::getPlanStartDate, startDate);
            queryWrapper.le(MesProductionPlanTask::getPlanStartDate, endDate);
            
            List<MesProductionPlanTask> tasks = mesProductionPlanTaskService.list(queryWrapper);
            
            // 统计任务状态
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalTasks", tasks.size());
            statistics.put("pendingTasks", tasks.stream().mapToInt(task -> task.getStatus() == 0 ? 1 : 0).sum());
            statistics.put("ongoingTasks", tasks.stream().mapToInt(task -> (task.getStatus() == 1 || task.getStatus() == 2) ? 1 : 0).sum());
            statistics.put("completedTasks", tasks.stream().mapToInt(task -> task.getStatus() == 3 ? 1 : 0).sum());
            
            // 计算工作时长（基于实际开始和结束时间）
            double totalWorkHours = 0.0;
            for (MesProductionPlanTask task : tasks) {
                if (task.getActualStartDate() != null && task.getActualEndDate() != null) {
                    long diffMs = task.getActualEndDate().getTime() - task.getActualStartDate().getTime();
                    double hours = diffMs / (1000.0 * 60 * 60);
                    totalWorkHours += Math.max(0, hours);
                }
            }
            statistics.put("workHours", Math.round(totalWorkHours * 10) / 10.0);
            
            return Result.OK(statistics);
        } catch (Exception e) {
            log.error("获取员工工作统计数据失败", e);
            return Result.error("获取员工工作统计数据失败：" + e.getMessage());
        }
    }

}
